package com.hmyd.hmyd_android.shop;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hmyd.hmyd_android.R;
import com.hmyd.hmyd_android.adapter.JfMallItemAdapter;
import com.hmyd.hmyd_android.commons.UrlConstant;
import com.hmyd.hmyd_android.dto.DtoInfoNoPage;
import com.hmyd.hmyd_android.dto.JfMallItemDto;
import com.hmyd.hmyd_android.dto.Page;
import com.hmyd.hmyd_android.dto.myenum.JfMallSortEnum;
import com.hmyd.hmyd_android.fragment.BasicFragmentList;
import com.hmyd.hmyd_android.view.PullToRefreshBase;
import com.hmyd.hmyd_android.view.PullToRefreshGridView;
import com.hmyd.hmyd_android.view.PullToRefreshBase.OnRefreshListener2;
import com.hmyd.hmyd_android.weigets.ILoadingLayout;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

/**
 * 实物商品
 * 
 * @author wangk
 * 
 */
public class PhysicalGoodsFragment extends BasicFragmentList {

	private LinkedList<JfMallItemDto> datas = new LinkedList<JfMallItemDto>();
	private PullToRefreshGridView mPullRefreshListView;
	private JfMallItemAdapter mAdapter;
	private View rootView;

	private final int REFRESH = 1;
	private final int LOADMORE = 2;

	protected boolean hasMore = false;
	private String cursorId;
	private String lastPrice;
	String sort = "default";
	boolean isNewSort = false;

	// 广播接收排序请求
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (datas.isEmpty()) {
				return;
			}
			if (intent.getAction().equals("sort")) {
				sort = intent.getStringExtra("sort");
				String category = intent.getStringExtra("category");
				RequestParams params = new RequestParams();
				params.addBodyParameter("category", "goods");
				params.addBodyParameter("sort", sort);
				if (sort.equals(JfMallSortEnum.PRICEASCENDING)) {
					lastPrice = String.valueOf(-1);
					params.addBodyParameter("integral", lastPrice);
				} else if (sort.equals(JfMallSortEnum.PRICEDESCENDING)) {
					lastPrice = String.valueOf(2147483647); // 赋予int最大常量
					params.addBodyParameter("integral", lastPrice);
				}
				cursorId = null; // 游标赋为空，防止数据错加载下一页
				if (category.equals("goods")) {
					onRequest(REFRESH, UrlConstant.SHOPLIST, HttpMethod.GET,
							params);
				}
			}
			else if (intent.getAction().equals("topG")) {
				mPullRefreshListView.backTop();
			} else if (intent.getAction().equals("collected")) {
				for (JfMallItemDto jfMallItemDto : datas) {
					String id = intent.getStringExtra("id");
					boolean isCollection = intent.getBooleanExtra(
							"isCollection", false);
					if (jfMallItemDto.id.equals(id)) {
						jfMallItemDto.isCollection = isCollection;
					}
				}
				mAdapter.notifyDataSetChanged();
				mPullRefreshListView.invalidate();
			}
		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.frgament_physical_goods,
				container, false);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		initViews();
		IntentFilter filter = new IntentFilter("sort");
		filter.addAction("newSort");
		filter.addAction("topG");
		filter.addAction("collected");
		getActivity().registerReceiver(receiver, filter);

		RequestParams params = new RequestParams();
		params.addBodyParameter("sort", sort);
		params.addBodyParameter("category", "goods");
		onRequest(REFRESH, UrlConstant.SHOPLIST, HttpMethod.GET, params);
	}

	private void initViews() {
		// 得到控件
		mPullRefreshListView = (PullToRefreshGridView) rootView
				.findViewById(R.id.pull_refresh_grid);

		initIndicator();

		mAdapter = new JfMallItemAdapter(getActivity(), datas);
		mPullRefreshListView.setAdapter(mAdapter);

		mPullRefreshListView
				.setOnRefreshListener(new OnRefreshListener2<GridView>() {

					@SuppressLint("SimpleDateFormat")
					@Override
					public void onPullDownToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						// 刷新
						SimpleDateFormat myFmt = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");

						String label = myFmt.format(new Date(System
								.currentTimeMillis()));

						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						RequestParams params = new RequestParams();
						params.addBodyParameter("sort", sort);
						params.addBodyParameter("category", "goods");
						if (sort.equals(JfMallSortEnum.PRICEASCENDING)) {
							lastPrice = String.valueOf(-1);
							params.addBodyParameter("integral", lastPrice);
						} else if (sort.equals(JfMallSortEnum.PRICEDESCENDING)) {
							lastPrice = String.valueOf(2147483647); // 赋予int最大常量
							params.addBodyParameter("integral", lastPrice);
						}
						cursorId = null;// 游标赋为空，防止数据错加载下一页
						onRequest(REFRESH, UrlConstant.SHOPLIST,
								HttpMethod.GET, params);
					}

					@SuppressLint("SimpleDateFormat")
					@Override
					public void onPullUpToRefresh(
							PullToRefreshBase<GridView> refreshView) {
						// 加载更多
						SimpleDateFormat myFmt = new SimpleDateFormat(
								"yyyy-MM-dd HH:mm:ss");

						String label = myFmt.format(new Date(System
								.currentTimeMillis()));

						refreshView.getLoadingLayoutProxy()
								.setLastUpdatedLabel(label);

						if (hasMore) {
							RequestParams params = new RequestParams();
							if (sort.equals(JfMallSortEnum.MDEFAULT)) {
								params.addBodyParameter("lastCursor", cursorId);
							} else {
								params.addBodyParameter("integral", lastPrice);
							}
							params.addBodyParameter("sort", sort);
							params.addBodyParameter("category", "goods");
							onRequest(LOADMORE, UrlConstant.SHOPLIST,
									HttpMethod.GET, params);
						} else {
							mPullRefreshListView.onRefreshComplete();
						}

					}
				});

		mPullRefreshListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String idString = datas.get(position).id;
				Intent intent = new Intent();
				intent.setClass(getActivity(), GoodsDetailsActivity.class);
				intent.putExtra("id", idString);
				startActivity(intent);
			}
		});
	}

	private void initIndicator() {

		ILoadingLayout startLabels = mPullRefreshListView
				.getLoadingLayoutProxy(true, false);
		startLabels.setPullLabel("下拉可以刷新");// 刚下拉时，显示的提示
		startLabels.setRefreshingLabel("加载中");// 刷新时
		startLabels.setReleaseLabel("松开可以刷新");// 下来达到一定距离时，显示的提示

		ILoadingLayout endLabels = mPullRefreshListView.getLoadingLayoutProxy(
				false, true);
		endLabels.setPullLabel("更多");// 刚下拉时，显示的提示
		endLabels.setRefreshingLabel("加载中");// 刷新时
		endLabels.setReleaseLabel("松开可以加载更多");// 下来达到一定距离时，显示的提示

	}

	@Override
	public void onPostSuccess(int postId, String result) {
		Gson gson = new Gson();
		java.lang.reflect.Type type = new TypeToken<DtoInfoNoPage<Page<JfMallItemDto>>>() {
		}.getType();
		DtoInfoNoPage<Page<JfMallItemDto>> dtoInfoNoPage1 = gson.fromJson(result, type);
		Page<JfMallItemDto> page = dtoInfoNoPage1.data;
		hasMore = page.hasMore;
		if (page != null && page.records != null) {

			switch (postId) {
			case REFRESH:
				datas.clear();
				datas.addAll(page.records);
				break;
			case LOADMORE:
				datas.addAll(page.records);
				break;
			default:
				break;
			}

			if (datas.size() > 0) {
				cursorId = String
						.valueOf(datas.get(datas.size() - 1).createdTime);
				lastPrice = String
						.valueOf(datas.get(datas.size() - 1).presentPrice);
			} else {
				cursorId = null;
				lastPrice = null;
			}
			mAdapter.notifyDataSetChanged();
			mPullRefreshListView.onRefreshComplete();
		}
	}

	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(receiver);
		super.onDestroy();
	}
}
